/**
 * 
 */
package com.feib.stms.service.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;


import org.springframework.stereotype.Service;


import com.feib.stms.dao.UploadFileActionLogDao;
import com.feib.stms.dao.UploadFileDao;
import com.feib.stms.dao.UploadFileTodoListDao;
import com.feib.stms.dao.UserDao;
import com.feib.stms.model.MailQueue;
import com.feib.stms.model.MenuItem;
import com.feib.stms.model.UploadFile;
import com.feib.stms.model.UploadFileActionLog;
import com.feib.stms.model.UploadFileTodoList;
import com.feib.stms.model.User;
import com.feib.stms.pagination.PaginatedList;
import com.feib.stms.service.MailJobService;
import com.feib.stms.service.UploadFileService;
import com.feib.stms.util.MailContentTemplate;
import com.feib.stms.util.UserUtil;

/**
 * @author Jimmy Liu
 *
 */
@Service("uploadFileService")
public class UploadFileServiceImpl extends BaseServiceImpl implements UploadFileService {

	private static final long serialVersionUID = -6652637476489975798L;


	@Resource(name="mailJobService")
	private MailJobService mailJob;

	@Resource(name="htmlMailFolder")
	private String htmlMailFolder;

	@Resource(name="defaultMailFrom")
	private String defaultMailFrom;

	@Resource(name="defaultMailReturnReceiptTo")
	private String defaultMailReturnReceiptTo;


	@Resource(name="uploadFileDao")
	private UploadFileDao uploadFileDao;

	@Resource(name="uploadFileActionLogDao")
	private UploadFileActionLogDao uploadFileActionLogDao;

	@Resource(name="uploadFileTodoListDao")
	private UploadFileTodoListDao uploadFileTodoListDao;

	@Resource(name="userDao")
	private UserDao userDao;


	/* (non-Javadoc)
	 * @see com.feib.stms.service.UploadFileService#findPaginatedListByUploadFile(com.feib.stms.model.UploadFile, java.util.Date, java.util.Date, java.util.List, com.feib.stms.pagination.PaginatedList)
	 */
	public PaginatedList<UploadFile> findPaginatedListByUploadFile(
			UploadFile uploadFile, Date uploaddDateFrom, Date uploadDateTo,
			Date deliveryDateFrom, Date deliveryDateTo, List<String> fileFormats, PaginatedList paginatedList) {

		return uploadFileDao.queryForPaginatedListByUploadFile(uploadFile, uploaddDateFrom, uploadDateTo, deliveryDateFrom, deliveryDateTo, fileFormats, paginatedList);
	}


	public UploadFile findUploadFileByPk(Long uploadFilePk) {

		return uploadFileDao.getUploadFileByPk(uploadFilePk);
	}

	/* (non-Javadoc)
	 * @see com.feib.stms.service.UploadFileService#findPaginatedListByUploadFile(com.feib.stms.model.UploadFile, java.util.Date, java.util.Date, java.util.List, com.feib.stms.pagination.PaginatedList)
	 */
	public PaginatedList<UploadFile> findPaginatedListDealUploadFile(
			UploadFile uploadFile, Date uploaddDateFrom, Date uploadDateTo,
			List<String> fileFormats, List<Integer> fileStatus, PaginatedList paginatedList) {

		return uploadFileDao.queryForPaginatedListDealUploadFile(uploadFile, uploaddDateFrom, uploadDateTo, fileFormats , fileStatus, paginatedList);
	}


	public void doCancelUploadFile(List<UploadFile> checkUploadFile) {

		/* 取消不用清除該檔案待辦事項,取消時無該檔案待辦事項 */

		/* 取得使用者操作資訊 */
		User user= UserUtil.getUser();
		Date sysdate=new Date();

		if (null == checkUploadFile || 0 == checkUploadFile.size())
			return ;  
		for(UploadFile uploadFile :checkUploadFile)
		{
			if (null != uploadFile  ){

				/* 新增檔案操作紀錄  */
				UploadFileActionLog uploadFileActionLog=new UploadFileActionLog();
				uploadFileActionLog.setUploadFile(uploadFile);
				uploadFileActionLog.setAction(UploadFileActionLog.UPLOAD_FILE_ACTION_LOG_CANCEL);
				uploadFileActionLog.setActionTime(sysdate);
				uploadFileActionLog.setUser(user);
				uploadFileActionLogDao.insert(uploadFileActionLog);

				/* 塞需要更新的檔案資料 */  
				uploadFile.setCancelUser(user);
				uploadFile.setCancelDate(sysdate);
				uploadFile.setUpdatedBy(user.getGroup().getGroupNo() + "_" + user.getUserId());
				uploadFile.setUpdatedDate(sysdate);
				uploadFile.setFileStatus(70);//70: 已取消(即放行後反悔，要刪除；明細應註記為刪除)

				/* 取消不用新增待辦事項 */

				/* 更新檔案狀態  */
				uploadFileDao.updateUploadFileFileStatus(uploadFile);

			}
		} 


	}


	public void doCheckUploadFile(List<UploadFile> checkUploadFile,Long menuItemPk,List<String> actions) {


		/* 取得使用者操作資訊 */
		User user= UserUtil.getUser();
		Date sysdate=new Date();
		int checkCount=0;
		int realCount=0;

		if (null == checkUploadFile || 0 == checkUploadFile.size())
			return ;  
		for(UploadFile uploadFile :checkUploadFile)
		{
			if (null != uploadFile && null !=uploadFile.getUploadFilePk() ){
				logger.debug("清除該檔案待辦事項");
				/* 清除該檔案待辦事項  */
				uploadFileTodoListDao.delete(uploadFile.getUploadFilePk());

				checkCount=uploadFileDao.getUploadFileCheckCount(uploadFile.getUploadFilePk());


				/* 塞需要更新的檔案資料 */  
				uploadFile.setUpdatedBy(user.getGroup().getGroupNo() + "_" + user.getUserId());
				uploadFile.setUpdatedDate(sysdate);
				uploadFile.setFileStatus(10);// 10: 審查中(已有人員審查，但未達到審查人數門檻)

				logger.debug("新增檔案操作紀錄");
				/* 新增檔案操作紀錄  */
				UploadFileActionLog uploadFileActionLog=new UploadFileActionLog();
				uploadFileActionLog.setUploadFile(uploadFile);

				uploadFileActionLog.setAction(UploadFileActionLog.UPLOAD_FILE_ACTION_LOG_CHECK);//審查

				uploadFileActionLog.setActionTime(sysdate);
				uploadFileActionLog.setUser(user);		
				uploadFileActionLogDao.insert(uploadFileActionLog);


				realCount=uploadFileActionLogDao.countUploadFileActionLog(uploadFile.getUploadFilePk(), actions, user.getUserPk());

				/* 已通過審查門檻  需紀錄最後審查人員與日期 */
				if(realCount>=checkCount){
					uploadFile.setCheckUser(user);
					uploadFile.setCheckDate(sysdate);
					uploadFile.setCheckResult(Boolean.TRUE);
					uploadFile.setFileStatus(30);// 30: 已審查/待放行(檔案審查通過，所有審查人員皆對檔案審查通過)
					/* 新增該檔案待辦事項  待放行 */
					UploadFileTodoList uploadFileTodoList=new UploadFileTodoList();
					MenuItem menuItem=new MenuItem();
					menuItem.setMenuItemPk(menuItemPk);
					uploadFileTodoList.setMenuItem(menuItem);
					uploadFileTodoList.setUploadFile(uploadFile);
					uploadFileTodoList.setGroup(user.getGroup());
					uploadFileTodoList.setSecuritiesNo(uploadFile.getSecuritiesNo());		
					uploadFileTodoListDao.addUploadFileTodoList(uploadFileTodoList);


					/* 依檔案 個別發送mail */				
					List<String> emails = userDao.findUserEmailByGroupMenuId(user.getGroup(), menuItemPk, uploadFile.getUploadFilePk());
					if (null != emails && 0 != emails.size())
					{

						StringBuffer mailTo = new StringBuffer();
						for(String email : emails)
							mailTo.append(email).append(",");
						logger.debug("發送mail {}",mailTo);
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

						String messageTile = " 您有 放行作業 待執行";
						StringBuffer paragraph1 = new StringBuffer();
						paragraph1.append(UserUtil.getUser().getUserName()).append(" 於 ").append(dateFormat.format(new Date()));
						paragraph1.append(" 審查 ").append(uploadFile.getFileName()).append("， 待您確認放行。");
						paragraph1.append("<br/>請您至系統確認資料內容。");
						String[] paragraphs = new String[]{"您好", paragraph1.toString(), "謝謝"};

						MailContentTemplate mailContentTemplate = new MailContentTemplate(messageTile, paragraphs, htmlMailFolder);
						MailQueue mailQueue;
						try {
							mailQueue = mailContentTemplate.createMailQueue();

							mailQueue.setMailTo(mailTo.toString());
							mailQueue.setMailFrom(defaultMailFrom);
							mailQueue.setMailReturnReceiptTo(defaultMailReturnReceiptTo);
							mailQueue.setMailStatus(0);
							mailJob.createAndSend(mailQueue);
							mailQueue = null; // free resource
						}catch (Exception e) {
							logger.error("", e);
						}

					}

				}

				uploadFileDao.updateUploadFileFileStatus(uploadFile);




			}
		}
	}


	public void doConfirmUploadFile(List<UploadFile> checkUploadFile,List<String> actions, String signerCert) {		


		/* 取得使用者操作資訊 */
		User user= UserUtil.getUser();
		Date sysdate=new Date();

		int confirmCount=0;//檔案放行設定數目
		int realCount=0;//實際放行次數

		if (null == checkUploadFile || 0 == checkUploadFile.size())
			return ;  
		for(UploadFile uploadFile :checkUploadFile)
		{
			if (null != uploadFile  ){
				/* 清除該檔案待辦事項  */
				uploadFileTodoListDao.delete(uploadFile.getUploadFilePk());

				/* 檔案放行設定數目 */
				confirmCount=	uploadFileDao.getUploadFileConfirmCount(uploadFile.getUploadFilePk());

				/* 塞需要更新的檔案資料 */
				uploadFile.setUpdatedBy(user.getGroup().getGroupNo() + "_" + user.getUserId());
				uploadFile.setUpdatedDate(sysdate);
				uploadFile.setFileStatus(40);// 40: 放行中(已有人員放行，但未達到放行人數門檻)
				uploadFile.setSignerCert(signerCert);

				/* 新增檔案操作紀錄  */
				UploadFileActionLog uploadFileActionLog=new UploadFileActionLog();
				uploadFileActionLog.setUploadFile(uploadFile);
				uploadFileActionLog.setAction(UploadFileActionLog.UPLOAD_FILE_ACTION_LOG_CONFIRM);//放行

				uploadFileActionLog.setActionTime(sysdate);
				uploadFileActionLog.setUser(user);		
				uploadFileActionLogDao.insert(uploadFileActionLog);

				/* 實際放行次數 */
				realCount=uploadFileActionLogDao.countUploadFileActionLog(uploadFile.getUploadFilePk(), actions, user.getUserPk());

				/* 已通過放行門檻  需紀錄最後放行人員與日期 */
				if(realCount>=confirmCount){
					uploadFile.setConfirmUser(user);
					uploadFile.setConfirmDate(sysdate);
					uploadFile.setConfirmResult(Boolean.TRUE);
					uploadFile.setFileStatus(60);// 60: 已放行/待預約(即全數放行通過)

				}
				/*放行不用 新增待辦事項 因為目前沒有下一部人工動作 */

				uploadFileDao.updateUploadFileFileStatus(uploadFile);
			}
		}

	}



	public int doDeleteUploadFile(Long uploadFilePk,Integer fileStatus) {

		User user= UserUtil.getUser();
		Date sysdate=new Date();

		UploadFile uploadFile= new UploadFile();
		uploadFile.setUploadFilePk(uploadFilePk);
		uploadFile.setUpdatedBy(user.getGroup().getGroupNo() + "_" + user.getUserId());
		uploadFile.setUpdatedDate(sysdate);
		uploadFile.setFileStatus(fileStatus);

		/* 新增檔案操作紀錄  */
		UploadFileActionLog uploadFileActionLog=new UploadFileActionLog();
		uploadFileActionLog.setUploadFile(uploadFile);
		if(50==fileStatus) {//50: 已刪除/不放行(只要有一人不放行，即為放行不通過；明細應註記為刪除)
			uploadFileActionLog.setAction(UploadFileActionLog.UPLOAD_FILE_ACTION_LOG_CONFIRM_DELETE);
			uploadFile.setConfirmUser(user);
			uploadFile.setConfirmDate(sysdate);
			uploadFile.setConfirmResult(Boolean.FALSE);
		}else if(20==fileStatus) {// 20: 已刪除/審查不通過(只要有一人審查不通過，即為審查不通過；明細應註記為刪除)
			uploadFileActionLog.setAction(UploadFileActionLog.UPLOAD_FILE_ACTION_LOG_CHECK_DELETE);
			uploadFile.setCheckUser(user);
			uploadFile.setCheckDate(sysdate);
			uploadFile.setCheckResult(Boolean.FALSE);

		}
		uploadFileActionLog.setActionTime(sysdate);
		uploadFileActionLog.setUser(user);		
		uploadFileActionLogDao.insert(uploadFileActionLog);

		/*刪除不用 新增待辦事項  */

		return  uploadFileDao.updateUploadFileFileStatus(uploadFile);
	}





	public int findUploadFileCheckCount(Long uploadFilePk) {

		return uploadFileDao.getUploadFileCheckCount(uploadFilePk);
	}


	public int findUploadFileConfirmCount(Long uploadFilePk) {

		return uploadFileDao.getUploadFileConfirmCount(uploadFilePk);
	}


	public int updateUploadFileStatus(Long uploadFilePk, Integer fileStatus) {
		UploadFile uploadFile = new UploadFile();
		uploadFile.setUploadFilePk(uploadFilePk);
		uploadFile.setFileStatus(fileStatus);      
		User user= UserUtil.getUser();
		uploadFile.setConfirmUser(user);
		uploadFile.setConfirmDate(new Date());
		uploadFile.setUpdatedBy(user.getGroup().getGroupNo() + "_" + user.getUserId());
		uploadFile.setUpdatedDate(new Date());
		return uploadFileDao.updateUploadFileFileStatus(uploadFile);

	}








}
